<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>哈哈</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .box {
            width: 350px;
            height: 350px;
            margin: 100px;
            border: 1px solid #ccc;
            position: relative;
        }

        .big {
            width: 400px;
            height: 400px;
            position: absolute;
            top: 0;
            left: 360px;
            border: 1px solid #ccc;
            overflow: hidden;
            display: none;
        }

        .mask {
            width: 175px;
            height: 175px;
            background: rgba(255, 255, 0, 0.4);
            position: absolute;
            top: 0px;
            left: 0px;
            cursor: move;
            display: none;
        }

        .small {
            position: relative;
        }
    </style>
</head>
<body>
<div class="box" id="box">
    <div class="small"><!--小层-->
        <img src="images/small.png" width="350" alt=""/>
        <div class="mask"></div><!--遮挡层-->
    </div>
    <div class="big"><!--大层-->
        <img src="images/big.jpg" width="800" alt=""/><!--大图-->
    </div>
</div>
<!--导入外部的script文件-->
<script src="common.js"></script>
<script>
    //获取box层
    var box=my$("box");
    //获取小层
    var small=box.children[0];
    //获取遮挡层
    var mask=small.children[1];
    //获取大层
    var big=box.children[1];
    //获取图片
    var img=big.children[0];
    //注册鼠标进入事件：显示遮挡层和大层
    box.onmouseover=function(){
        mask.style.display="block";//遮挡层
        big.style.display="block";//大层
    };
    //鼠标离开：隐藏遮挡层和大层
    box.onmouseout=function(){
        mask.style.display="none";//遮挡层
        big.style.display="none";//大层
    };
    //注册遮挡层移动事件
    mask.onmousemove=function(e){
        //计算遮挡层移动范围
        var left= e.clientX-mask.offsetWidth/2;
        var top= e.clientY-mask.offsetHeight/2;
        var x=left-100;//父级元素的margin值会影响位置
        var y=top-100;
        //最小值
        x=x<0?0:x;
        y=y<0?0:y;
        //最大值
        x=x>small.offsetWidth-mask.offsetWidth?small.offsetWidth-mask.offsetWidth:x;
        y=y>small.offsetHeight-mask.offsetHeight?small.offsetHeight-mask.offsetHeight:y;
        //赋值
        mask.style.left=x+"px";
        mask.style.top=y+"px";
        //计算图片的移动距离
        //遮挡层移动距离/遮挡层的最大移动距离=图片的移动距离/图片的最大移动距离
        //遮挡层的移动距离：x和y
        //遮挡层的最大移动距离
        var maskMaxMove=small.offsetWidth=mask.offsetWidth;
        //图片的最大移动距离
        var imgMaxMove=img.offsetWidth-big.offsetWidth;
        var imgLeft=x*imgMaxMove/maskMaxMove;
        var imgTop=y*imgMaxMove/maskMaxMove;
        //赋值
        img.style.marginLeft=-imgLeft+"px";
        img.style.marginTop=-imgTop+"px";
    };






</script>
</body>
</html>
